﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Lavka.Models;

namespace Lavka.Core
{
    public class SearchHelper
    {
        public static List<Products> FindProducts(string reference, string name, string priceFrom, string priceTo, bool setsOnly, string brandId, LavkaDbEntities context)
        {
            
            decimal inf = string.IsNullOrEmpty(priceFrom) ? 0 : Convert.ToDecimal(priceFrom);
            decimal sup = string.IsNullOrEmpty(priceTo) ? 100000000 : Convert.ToDecimal(priceTo);
            List<Products> result = context.Products.ToList();
            if (!string.IsNullOrEmpty(brandId))
            {
                result = result.Where(p => p.BrandId == Convert.ToInt32(brandId)).ToList();
            }
            if(!string.IsNullOrEmpty(reference))
            {
                result = result.Where(p => p.Reference == reference).ToList();
            }
            if (!string.IsNullOrEmpty(name))
            {
                result = result.Where(p => p.Name == name).ToList();
            }

            if (result == null || result.Count == 0)
            {
                if (!string.IsNullOrEmpty(name))
                result = context.Products.Where(p => p.Name.Contains(name)).ToList();
                if (!string.IsNullOrEmpty(reference))
                    result = context.Products.Where(p => p.Name.Contains(reference)).ToList();
            }

            if (!string.IsNullOrEmpty(priceFrom) || !string.IsNullOrEmpty(priceTo))
                result = result.Where(p => p.Price > inf && p.Price < sup).ToList();

            return result;
        }
    }
}